package com.plian.system.service.pf.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.constant.pf.ScoringStatusConstant;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.entity.pf.BaseEvaluationScore;
import com.plian.system.entity.pf.BaseOfficeScore;
import com.plian.system.entity.pf.EvaluationScoreDetail;
import com.plian.system.entity.sys.Org;
import com.plian.system.mapper.pf.BaseEvaluationScoreMapper;
import com.plian.system.mapper.pf.BaseOfficeScoreMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.pf.IBaseEvaluationScoreService;
import com.plian.system.service.pf.IEvaluationScoreDetailService;
import com.plian.system.service.pf.IPerformanceScoreService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.pf.BaseEvaluationScoreVO;
import com.plian.system.vo.pf.ScoreMethodVO;
import com.plian.system.wrapper.pf.BaseEvaluationScoreWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * @Author: Take-off
 * @Description: TODO
 * @Date: 2023/1/28 10:32 AM
 * @Version: 1.0
 **/
@Slf4j
@Service
@AllArgsConstructor
public class BaseEvaluationScoreServiceImpl extends BaseServiceImpl<BaseEvaluationScoreMapper, BaseEvaluationScore> implements IBaseEvaluationScoreService, BaseFlowService {

    private FormWorkflowService formWorkflowService;

    private IFormCodeService formCodeService;

    private BaseEvaluationScoreWrapper baseEvaluationScoreWrapper;

    private IEvaluationScoreDetailService evaluationScoreDetailService;

    private IOrgService orgService;

    private GzwProperties gzwProperties;

    private IPerformanceScoreService performanceScoreService;

    private BaseOfficeScoreMapper baseOfficeScoreMapper;

    @Override
    public boolean saveOrUpdate(BaseEvaluationScore baseEvaluationScore) {
        if (!Optional.ofNullable(baseEvaluationScore.getStatus()).isPresent()){
            baseEvaluationScore.setStatus(FormStatusConstant.UNREVIEWED);
        }
        if (baseEvaluationScore.getStatus().equals(FormStatusConstant.REJECT)){
            baseEvaluationScore.setStatus(FormStatusConstant.UNREVIEWED);
        }
        if (!Optional.ofNullable(baseEvaluationScore.getId()).isPresent()) {
            baseEvaluationScore.setCode(formCodeService.getCode(FormTypeConstant.PF_BASE_EVALUATION));
            baseEvaluationScore.setFormType(String.valueOf(FormTypeConstant.PF_BASE_EVALUATION));
        }
        return super.saveOrUpdate(baseEvaluationScore);
    }

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public boolean deleteLogic(List<Long> ids) {
        for (Long id : ids) {
            BaseEvaluationScore baseEvaluationScore = getById(id);
            if (baseEvaluationScore == null) {
                return false;
            } else if (baseEvaluationScore.getStatus() != null &&
                    (baseEvaluationScore.getStatus() != FormStatusConstant.STASH && baseEvaluationScore.getStatus() != FormStatusConstant.UNREVIEWED)) {
                return false;
            }
            formWorkflowService.deleteProcessInstance(String.valueOf(id));
        }

        boolean result = super.deleteLogic(ids);
        if (result){
            evaluationScoreDetailService.deleteByParentId(ids);
        }
        return result;
    }

    @Override
    public HashMap<String,Object> commit(String id) {
        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);

        //将需要提交的流程变量返回，用于工作流侧
        return new HashMap<String,Object>();
    }

    @Override
    public Boolean finish(String id) {
        Boolean result = handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
        if (result){
            //自动生成责任处室评分
            saveBaseOfficeScore(getById(id));
        }
        return result;
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 保存责任处室评分
     * @Date: 3:51 PM 2023/1/31
     * @Param: [baseEvaluationScore]
     * @return: void
     **/
    private void saveBaseOfficeScore(BaseEvaluationScore baseEvaluationScore){
        List<BaseOfficeScore> baseOfficeScores = setBaseOfficeScores(baseEvaluationScore);
        if (CollectionUtil.isNotEmpty(baseOfficeScores)){
            baseOfficeScores.forEach(baseOfficeScore -> {
                baseOfficeScoreMapper.insert(baseOfficeScore);
            });
        }
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 构建责任处室评分
     * @Date: 3:49 PM 2023/1/31
     * @Param: [baseEvaluationScore]
     * @return: java.util.List<com.plian.system.entity.pf.BaseOfficeScore>
     **/
    private List<BaseOfficeScore> setBaseOfficeScores(BaseEvaluationScore baseEvaluationScore){
        List<BaseOfficeScore> baseOfficeScores = new ArrayList<>();
        //获取企业下是否有责任处室
        List<BaseOfficeScore> baseOfficeScoreList = baseOfficeScoreMapper.selectList(new LambdaQueryWrapper<BaseOfficeScore>().eq(BaseOfficeScore::getFillingYear, baseEvaluationScore.getFillingYear())
                .eq(BaseOfficeScore::getFillingUnitId, baseEvaluationScore.getFillingUnitId()));
        if (CollectionUtil.isEmpty(baseOfficeScoreList)){
            //获取应该填写的责任处室
            Set<Long> officeIds = performanceScoreService.getAllScoreOffice(baseEvaluationScore.getFillingYear());
            if (CollectionUtil.isNotEmpty(officeIds)){
                officeIds.forEach(officeId ->{
                    //创建责任处室单据
                    BaseOfficeScore baseOfficeScore = new BaseOfficeScore();
                    baseOfficeScore.setFillingYear(baseEvaluationScore.getFillingYear());
                    baseOfficeScore.setFillingUnitId(baseEvaluationScore.getFillingUnitId());
                    baseOfficeScore.setOfficeId(officeId);
                    baseOfficeScore.setFormType(FormTypeConstant.PF_BASE_OFFICE +"");
                    baseOfficeScore.setEvaluationId(baseEvaluationScore.getId());
                    baseOfficeScore.setFillingUnitId(baseEvaluationScore.getFillingUnitId());
                    baseOfficeScore.setIsDeleted(0);
                    baseOfficeScore.setStatus(FormStatusConstant.STASH);
                    baseOfficeScore.setScoreStatus(ScoringStatusConstant.COMPANIES_HAVE_RATED);
                    baseOfficeScores.add(baseOfficeScore);
                });
            }
        }
        return baseOfficeScores;
    }

    @Override
    public Boolean reject(String id, int formState,String comment) {
        return handleStatus(Long.valueOf(id), formState);
    }

    @Override
    public void goBackToStash(String formId) {
        handleStatus(Long.valueOf(formId), UNREVIEWED);
    }

    /**
     * 统一处理状态机事件方法
     *
     * @param id          主键
     * @param updateStatus  更新状态
     * @return boolean
     */
    private Boolean handleStatus(Long id, int updateStatus) {
        try {
            BaseEvaluationScore baseEvaluationScore = getById(id);
            /**
             * 设置审批人和审批时间
             */
            if (updateStatus == FormStatusConstant.FINISH){
                baseEvaluationScore.setApprovedUser(TokenUtil.getTokenUserId());
                Date now = DateUtil.now();
                baseEvaluationScore.setApprovedTime(now);
            }
            baseEvaluationScore.setStatus(updateStatus);
            updateById(baseEvaluationScore);
            return true;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return false;
        }
    }

    @Override
    public List<PageData> findByIds(List<String> formIds) {
        LambdaQueryWrapper<BaseEvaluationScore> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(BaseEvaluationScore::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
        List<BaseEvaluationScore> evaluationScores = list(queryWrapper);
        List<BaseEvaluationScoreVO> baseEvaluationScoreVOS = baseEvaluationScoreWrapper.entityToVO(evaluationScores);
        List<PageData> pageDataList = new ArrayList<>();
        try{
            if (CollectionUtil.isNotEmpty(baseEvaluationScoreVOS)){
                for (BaseEvaluationScoreVO vo : baseEvaluationScoreVOS){
                    PageData pd = new PageData();
                    pd.put("id", vo.getId());
                    pd.put("UNITNAME", vo.getFillingUnitName());
                    pd.put("APPLICANTNAME", vo.getCreateUserName());
                    pd.put("applicantId", vo.getCreateUser());
                    pd.put("applyOrganizationId", vo.getFillingUnitId());
                    pd.put("formType", FormTypeConstant.PF_BASE_EVALUATION);
                    pd.put("orgName", vo.getFillingUnitName());
                    pageDataList.add(pd);
                }
            }

            return pageDataList;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return pageDataList;
    }

    @Override
    public List<Integer> getFormType() {
        return Arrays.asList(FormTypeConstant.PF_BASE_EVALUATION);
    }

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public boolean submit(BaseEvaluationScore baseEvaluationScore) {
        boolean result = saveOrUpdate(baseEvaluationScore);
        if (result) {
            String fillingUnitId = baseEvaluationScore.getFillingUnitId();
            Org org = orgService.getById(fillingUnitId);
            List<EvaluationScoreDetail> evaluationScoreDetails = baseEvaluationScore.getEvaluationScoreDetails();
            if (CollectionUtil.isNotEmpty(evaluationScoreDetails)){
                for (EvaluationScoreDetail detail : evaluationScoreDetails){
                    if (detail.getId() != null &&
                            Optional.ofNullable(detail.getIsDeleted()).isPresent() && detail.getIsDeleted().intValue() == 1) {
                        evaluationScoreDetailService.removeById(detail.getId());
                    }else {
                        if (!Optional.ofNullable(detail.getBaseScoreId()).isPresent()){
                            detail.setBaseScoreId(baseEvaluationScore.getId());
                            detail.setFillingUnitId(fillingUnitId);
                            detail.setFillingUnitName(org.getName());
                        }
                        evaluationScoreDetailService.saveOrUpdate(detail);
                    }
                }
            }
        }
        return result;
    }

    @Override
    public R<BaseEvaluationScoreVO> getDetailObj(BaseEvaluationScore baseEvaluationScore) {
        BaseEvaluationScoreVO baseEvaluationScoreVO = new BaseEvaluationScoreVO();
        Long baseId = baseEvaluationScore.getId();
        if (Optional.ofNullable(baseId).isPresent()){
            baseEvaluationScore = getById(baseId);
            baseEvaluationScoreVO = baseEvaluationScoreWrapper.entityToVO(baseEvaluationScore);
            //评分细则
            List<EvaluationScoreDetail> details = evaluationScoreDetailService.list(new LambdaQueryWrapper<EvaluationScoreDetail>().eq(EvaluationScoreDetail::getBaseScoreId, baseId));
            if (CollectionUtil.isNotEmpty(details)){
                //附件
                evaluationScoreDetailService.setFiles(details);
                baseEvaluationScoreVO.setEvaluationScoreDetails(details);
            }
        }
        //考核评分办法
        List<ScoreMethodVO> allScoreMethod = performanceScoreService.getAllScoreMethod(baseEvaluationScore.getFillingYear());
        baseEvaluationScoreVO.setScoreMethodVOS(allScoreMethod);
        return R.data(baseEvaluationScoreVO);
    }

    @Override
    public ListResult<BaseEvaluationScoreVO> list(Query query){
        List<SearchEntity> entityList = query.getSearch();
        if (query.getAscs()==null&&query.getDescs()==null){
            query.setDescs("create_time");
        }
        QueryWrapper<BaseEvaluationScore> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new BaseEvaluationScore()), entityList
        );
        //根据登陆权限
        String orgId = TokenUtil.getTokenOrgId();
        if (Optional.ofNullable(orgId).isPresent() && !orgId.equals(gzwProperties.getId()) && !orgId.equals(gzwProperties.getReportId())){
            queryWrapper.eq("filling_unit_id",orgId);
        }

        IPage<BaseEvaluationScore> pages = page(Condition.getPage(query), queryWrapper);
        List<BaseEvaluationScoreVO> evaluationScoreVOS = baseEvaluationScoreWrapper.entityToVO(pages.getRecords());

        ListResult<BaseEvaluationScoreVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(evaluationScoreVOS);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }

}
